// 实习控制器
package org.example.backend.controller;

import org.example.backend.dto.InternshipDetailDto;
import org.example.backend.dto.PageResponseDto;
import org.example.backend.dto.StudentInternshipInfoDto;
import org.example.backend.entity.*;
import org.example.backend.exception.BusinessException;
import org.example.backend.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/internships")
@CrossOrigin
public class InternshipController {

    private static final Logger logger = LoggerFactory.getLogger(InternshipController.class);

    private final InternshipService internshipService;
    private final StudentService studentService;
    private final TeacherService teacherService;
    private final UserService userService;
    private final CompanyService companyService;

    public InternshipController(InternshipService internshipService,
                                StudentService studentService,
                                TeacherService teacherService,
                                UserService userService, CompanyService companyService) {
        this.internshipService = internshipService;
        this.studentService = studentService;
        this.teacherService = teacherService;
        this.userService = userService;
        this.companyService = companyService;
    }


    /**
     * 教师/管理员分配指导教师
     */
    @PutMapping("/{internshipId}/assign-teacher")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ResponseEntity<?> assignTeacher(@PathVariable Long internshipId,
                                         @RequestParam Long teacherId) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);

            Internship internship = internshipService.assignTeacher(internshipId, teacherId, currentUser.getId());

            Map<String, Object> response = new HashMap<>();
            response.put("message", "指导教师分配成功");
            response.put("internship", internship);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("分配指导教师失败", e);
            return ResponseEntity.badRequest().body("分配失败：" + e.getMessage());
        }
    }

    /**
     * 企业/管理员填写企业导师信息
     */
    @PutMapping("/{internshipId}/mentor-info")
    @PreAuthorize("hasRole('COMPANY') or hasRole('ADMIN')")
    public ResponseEntity<?> updateMentorInfo(@PathVariable Long internshipId,
                                            @RequestParam String mentorName,
                                            @RequestParam String mentorPhone,
                                            @RequestParam(required = false) String mentorEmail) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);

            Internship internship = internshipService.updateMentorInfo(internshipId, mentorName, mentorPhone, mentorEmail, currentUser.getId());

            Map<String, Object> response = new HashMap<>();
            response.put("message", "企业导师信息更新成功");
            response.put("internship", internship);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("更新企业导师信息失败", e);
            return ResponseEntity.badRequest().body("更新失败：" + e.getMessage());
        }
    }

    /**
     * 更新实习状态
     */
    @PutMapping("/{internshipId}/status")
    public ResponseEntity<?> updateInternshipStatus(@PathVariable Long internshipId,
                                                  @RequestParam Integer status) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User currentUser = userService.getUserByUsername(username);

            Internship internship = internshipService.updateInternshipStatus(internshipId, status, currentUser.getId());

            String statusMessage = "";
            switch (status) {
                case 0: statusMessage = "未开始"; break;
                case 1: statusMessage = "进行中"; break;
                case 2: statusMessage = "已完成"; break;
                case 3: statusMessage = "已终止"; break;
                default: statusMessage = "未知状态";
            }

            Map<String, Object> response = new HashMap<>();
            response.put("message", "实习状态更新为" + statusMessage);
            response.put("internship", internship);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            logger.error("更新实习状态失败", e);
            return ResponseEntity.badRequest().body("更新失败：" + e.getMessage());
        }
    }
    /**
     * 获取实习详情（包含关联信息）
     */
    @GetMapping("/{internshipId}")
    public ResponseEntity<?> getInternshipWithDetails(@PathVariable Long internshipId) {
        try {
            InternshipDetailDto internshipDto = internshipService.getInternshipWithDetails(internshipId);
            return ResponseEntity.ok(internshipDto);
        } catch (Exception e) {
            logger.error("获取实习详情失败", e);
            return ResponseEntity.badRequest().body("获取实习详情失败：" + e.getMessage());
        }
    }

    /**
     * 学生获取自己的实习列表（包含关联信息）
     */
    @GetMapping("/my")
    @PreAuthorize("hasRole('STUDENT')")
    public ResponseEntity<PageResponseDto<InternshipDetailDto>> getMyInternshipsWithDetails(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User user = userService.getUserByUsername(username);

            // 获取学生信息
            Student student = studentService.getStudentByUserId(user.getId());

            Page<InternshipDetailDto> internshipPage = internshipService.getInternshipsWithDetailsByStudent(
                    student.getId(), page, size);

            PageResponseDto<InternshipDetailDto> response = new PageResponseDto<>(
                    internshipPage.getContent(),
                    internshipPage.getTotalElements(),
                    internshipPage.getTotalPages(),
                    page,
                    size
            );

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取实习列表失败", e);
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 教师获取自己指导的实习列表（包含关联信息）
     */
    @GetMapping("/teacher")
    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<PageResponseDto<InternshipDetailDto>> getTeacherInternshipsWithDetails(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User user = userService.getUserByUsername(username);

            // 获取教师信息
            Teacher teacher = teacherService.getTeacherByUserId(user.getId());

            Page<InternshipDetailDto> internshipPage = internshipService.getInternshipsWithDetailsByTeacher(
                    teacher.getId(), page, size);

            PageResponseDto<InternshipDetailDto> response = new PageResponseDto<>(
                    internshipPage.getContent(),
                    internshipPage.getTotalElements(),
                    internshipPage.getTotalPages(),
                    page,
                    size
            );

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取实习列表失败", e);
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 企业获取相关的实习列表（包含关联信息）
     */
    @GetMapping("/company")
    @PreAuthorize("hasRole('COMPANY')")
    public ResponseEntity<PageResponseDto<InternshipDetailDto>> getCompanyInternshipsWithDetails(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            // 获取当前认证用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User user = userService.getUserByUsername(username);

            // 获取企业信息
            Company company = companyService.getCompanyByUserId(user.getId());

            Page<InternshipDetailDto> internshipPage = internshipService.getInternshipsWithDetailsByCompany(
                    company.getId(), page, size);
            PageResponseDto<InternshipDetailDto> response = new PageResponseDto<>(
                    internshipPage.getContent(),
                    internshipPage.getTotalElements(),
                    internshipPage.getTotalPages(),
                    page,
                    size
            );

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取实习列表失败", e);
            return ResponseEntity.badRequest().body(null);
        }
    }

    /**
     * 通过学生ID获取实习信息（仅包含学生ID、实习ID、岗位标题和公司名称）
     */
    @GetMapping("/student-info/{studentId}")
    public ResponseEntity<List<StudentInternshipInfoDto>> getStudentInternshipInfo(@PathVariable Long studentId) {
        try {
            List<StudentInternshipInfoDto> internshipInfo = internshipService.getStudentInternshipInfo(studentId);
            return ResponseEntity.ok(internshipInfo);
        } catch (Exception e) {
            logger.error("获取学生实习信息失败", e);
            return ResponseEntity.badRequest().body(null);
        }
    }


    /**
     * 管理员获取所有实习列表（包含关联信息）
     */
    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<PageResponseDto<InternshipDetailDto>> getAllInternshipsWithDetails(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<InternshipDetailDto> internshipPage = internshipService.getAllInternshipsWithDetails(page, size);

            PageResponseDto<InternshipDetailDto> response = new PageResponseDto<>(
                    internshipPage.getContent(),
                    internshipPage.getTotalElements(),
                    internshipPage.getTotalPages(),
                    page,
                    size
            );

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取实习列表失败", e);
            return ResponseEntity.badRequest().body(null);
        }
    }
}
